package com.ganee.agora.view

import android.media.MediaMetadataRetriever
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.util.Log
import android.view.View
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import cn.jzvd.Jzvd
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.ganee.agora.R
import com.ganee.agora.model.UploadFileRequestBody
import com.ganee.agora.utils.FileUtils
import com.ganee.agora.utils.GlideEngine
import com.ganee.agora.utils.Md5Util
import com.ganee.agora.viewmodel.VideoPlayerViewModel
import com.ganee.baselib.arouter.Constance
import com.ganee.baselib.httprequest.utils.ToastUtil
import com.ganee.baselib.mvvmlibrary.base.BaseActivity
import com.google.gson.Gson
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import com.qiniu.pili.droid.shortvideo.PLErrorCode.*
import com.qiniu.pili.droid.shortvideo.PLShortVideoTranscoder
import com.qiniu.pili.droid.shortvideo.PLVideoSaveListener
import com.yanzhenjie.album.Action
import com.yanzhenjie.album.Album
import com.yanzhenjie.album.AlbumFile
import com.yanzhenjie.album.Filter
import kotlinx.android.synthetic.main.activity_video_player.*
import kotlinx.android.synthetic.main.item_localimage.*
import okhttp3.MediaType
import okhttp3.RequestBody
import java.io.File


@Route(path = Constance.ACTIVITY_URL_VIDEO_PLAYER)
class VideoPlayerActivity : BaseActivity<VideoPlayerViewModel>(), View.OnClickListener {

    private var mFileName:String? = null
    private var isCompressing:Boolean = false
    private var videoUrl:String? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_video_player)
        ARouter.getInstance().inject(this)
        choose_video.setOnClickListener(this)
        take_video.setOnClickListener(this)
//        videoUrl = "http://114.215.25.163:7080/file/agora/active/20200322/10000000000000032-ireuI2F3mg-123.mp4"
//        videoPlayer.setUp(videoUrl, "")

    }
    override fun onPause() {
        super.onPause()
        Jzvd.releaseAllVideos()
    }

    override fun onBackPressed() {
        if (Jzvd.backPress()) {
            return
        }
        super.onBackPressed()
    }

    override fun getViewModel(): VideoPlayerViewModel {
        return ViewModelProviders.of(this@VideoPlayerActivity).get(VideoPlayerViewModel::class.java)
    }

    override fun onClick(v: View?) {
        when(v!!.id){
            R.id.choose_video -> {
                chooseVideo()
            }
            R.id.take_video -> {
                takeVideo()
            }
        }
    }

    private fun takeVideo() {
        Album.camera(this)
                .video()
                .quality(0) // Video quality, [0, 1].
                .limitDuration(30) // The longest duration of the video is in milliseconds.
                .limitBytes(15 * 1024 *1024)
                .onResult(Action<String>() {
                    Log.e("eee",it)
//                    startCompressed(it)
                    videoPlayer.setUp(it, "")
                })
                .onCancel(Action<String>() {

                })
                .start()
    }

    private fun chooseVideo() {
        PictureSelector.create(this@VideoPlayerActivity)
                .openGallery(PictureMimeType.ofVideo())
//                .openCamera(PictureMimeType.ofVideo()) // 单独拍照，也可录像或也可音频 看你传入的类型是图片or视频
                .loadImageEngine(GlideEngine.createGlideEngine()) // 外部传入图片加载引擎，必传项
                .maxSelectNum(5) // 最大图片选择数量
                .minSelectNum(1) // 最小选择数量
                .selectionMode(PictureConfig.MULTIPLE) // 多选 or 单选
                .previewImage(true) // 是否可预览图片
                .previewVideo(true) // 是否可预览视频
                .isCamera(false) // 是否显示拍照按钮
                .glideOverride(160, 160) // glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                .selectionMedia(mAdapter!!.data) // 是否传入已选图片
                .cutOutQuality(90) // 裁剪输出质量 默认100
                .minimumCompressSize(100) // 小于100kb的图片不压缩
                .videoQuality(1)// 视频录制质量 0 or 1
                .videoMaxSecond(15)////显示多少秒以内的视频or音频也可适用
                .forResult(object : OnResultCallbackListener<LocalMedia> {
                    override fun onResult(result: List<LocalMedia>) {

                    }

                    override fun onCancel() {

                    }
                })
    }

    private fun startCompressed(videoPath: String) {
        if (isCompressing) {
            return
        }
        showLoading()
        isCompressing = true
        val startTime = System.currentTimeMillis()
        mFileName = "$startTime.mp4"
        //PLShortVideoTranscoder初始化，三个参数，第一个context，第二个要压缩文件的路径，第三个视频压缩后输出的路径
        val mShortVideoTranscoder = PLShortVideoTranscoder(this, videoPath, getLocalFile().path)
        val retr = MediaMetadataRetriever()
        retr.setDataSource(videoPath)
        val height = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT) // 视频高度
        val width = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH) // 视频宽度
        val rotation = retr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION) // 视频旋转方向
        val transcodingBitrateLevel = 3

        mShortVideoTranscoder.transcode(width.toInt(), height.toInt(), FileUtils.getEncodingBitrateLevel(transcodingBitrateLevel), false, object : PLVideoSaveListener{
            override fun onSaveVideoSuccess(s: String?) {
                handler.sendEmptyMessage(103)
            }

            override fun onSaveVideoFailed(errorCode: Int) {
                //压缩失败
                isCompressing = false
                dismissLoading()
                runOnUiThread {
                    when (errorCode) {
                        ERROR_NO_VIDEO_TRACK -> {
                        }
                        ERROR_SRC_DST_SAME_FILE_PATH -> {
                        }
                        ERROR_LOW_MEMORY -> {
                        }
                        else -> {
                        }
                    }
                }
            }
            override fun onSaveVideoCanceled() {
                //取消压缩
                dismissLoading()
                handler.sendEmptyMessage(101)
            }
            override fun onProgressUpdate(percent: Float) {
                //压缩进度
                handler.sendEmptyMessage(100)
            }
        })
    }

    /**
     * 上传文件  active/uploadFile  参数：
     */
    private fun initUploadFile(path: String) {

        val belongType = "02"
        val fileType = "02"
        val fileName = mFileName
        val fileContent = Md5Util.file2Base64(path)
        val infoEntity = UploadFileRequestBody(belongType, fileType, fileName, fileContent)
        val body = Gson().toJson(infoEntity)
        val requestBody = RequestBody.create(MediaType.parse("application/json"), body)
        viewModel.postUploadFile(requestBody)

        viewModel.url.observe(this, Observer<String> {
            dismissLoading()
            videoUrl = it
//            videoPlayer.setUp(videoUrl, "")
        })
    }

    var handler = Handler(Handler.Callback { msg ->
        when (msg.what) {
            100 -> {

            }
            101 -> {

            }
            102 -> {

            }
            103 -> {
                dismissLoading()
                val compressedFilePath: String = getLocalFile().path
                ToastUtil.showToast("压缩后视频大小:" + FileUtils.getFormatSize(FileUtils.getFileSize(File(compressedFilePath)).toDouble()))
                Log.e("eee","压缩后视频大小:" + FileUtils.getFormatSize(FileUtils.getFileSize(File(compressedFilePath)).toDouble()))
//                videoPlayer.setUp(compressedFilePath, "")
                initUploadFile(compressedFilePath)
            }
        }
        false
    })

    private fun getLocalFile(): File {
        return File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), mFileName)
    }
}
